# import os
# from socket import *
import sys
sys.path.append(r'..')
import time
# import sys
# import argparse
from router.apis import Apis
from router.broker import Broker
from router.ddm import DDM


def module_set_ready(a):
    a.dout_set(21, 0)


def module_is_ready(a):
    module_state_map = {
        '000': 'Reserved',
        '001': 'LowPwr',
        '010': 'PwrUp',
        '011': 'Ready',
        '100': 'PwrDn',
        '101': 'Fault',
        '110': 'Reserved',
        '111': 'Reserved'
    }
    ret = a.get_twi(1, 0x3)
    ret1 = ret.split(',')[0]  #hex
    ret2 = int(ret1, 16)

    idx = '{:08b}'.format(ret2)[4:7]
    return module_state_map[idx]


def get_ddm_case_temp(a):
    b = Broker()
    b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
    d = DDM(b)
    return round(d.case_temp, 2)


def set_fan(a, fan):
    a.comm_cmdstr_setter('*FAN ' + str(fan))
    print("fan set: {}".format(fan))


# progress bar for sleep
# t: seconds
def bar(t):
    bar_len = 51
    for i in range(bar_len):
        print('\r Progess: {} {}'.format("#"*i, str(round(i/(bar_len-1) *100, 2)) +"%" ), end='')
        time.sleep(t/(bar_len-1))
        
    print("\r\n")


if __name__ == '__main__':
    print('api 111')

    a = Apis()

    print('api 222')
    target_ddm_temp = input("please enter target ddm temp:")

    #set fan to 50%
    set_fan(a, 50)

    # set module ready
    module_set_ready(a)

    # module ready?
    print("Wait module for ready ...")

    while True:
        bar(10)
        if module_is_ready(a) == "Ready":
            break

    print("Module is ready now!!!")

    # Read DDM temp and compare with target temp
    for fan in range(50, 0, -2):
        set_fan(a, 50)
        print('Set fan: {}'.format(fan))
        bar(30)
        ddm_case_temp = get_ddm_case_temp(a)
        print("Current ddm case temp:{}".format(ddm_case_temp))

        if ddm_case_temp - int(target_ddm_temp) < 0.5:
            print("The current temperature is almost equal to the preset temperature.")
            print("Fan is complete")
            print("Current fan: {}".format(fan))






